// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService;
using Microsoft.Security.Application;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks
{
    public partial class managegroups : System.Web.UI.Page
    {

        List<Group> lstGroups = null;

        public void Page_Error(object sender, EventArgs e)
        {
            if (Server.GetLastError() is HttpException)
            {
                throw new HttpException(((HttpException)Server.GetLastError()).GetHttpCode(), Server.GetLastError().Message);
            }
            else
                throw new HttpException(500, "Unhandled Exception.");
        }


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskAdmin")))
                throw new HttpException(403, "Requires Task Administrator Role");

            if (ViewState["Groups"] == null)
            {
                lstGroups = new List<Group>();
                TasksServiceClient tasksClient = new TasksServiceClient();
                lstGroups.AddRange(tasksClient.GetActiveGroups());
                ViewState["Groups"] = lstGroups;
                tasksClient.Close();
            }
            else
            {
                lstGroups = (List<Group>)ViewState["Groups"];
            }

            if (!Page.IsPostBack)
            {
                this.DoDataBind();
                lblPageHeader.Text = "Manage Task Groups";
            }

        }

        protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                foreach (System.Web.UI.Control BaseControl in e.Row.Cells[1].Controls)
                {
                    if (BaseControl.GetType().BaseType == typeof(LinkButton))
                    {
                        LinkButton linkBtn = (LinkButton)BaseControl;
                        if (linkBtn.CommandName == "Delete")
                            linkBtn.OnClientClick = "return confirm('" + Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "GRP_DEL_CONFIRM", 4) + "');";
                    }
                }

            }
        }

        protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["GridSortDirection"] != null)
                if (ViewState["GridSortDirection"].ToString() == SortDirection.Ascending.ToString())
                    e.SortDirection = SortDirection.Descending;
                else
                    e.SortDirection = SortDirection.Ascending;

            lstGroups.Sort(new GroupComparer(e.SortDirection, e.SortExpression));

            ViewState["GridSortDirection"] = e.SortDirection;
            ViewState["GridSortExpression"] = e.SortExpression;
            this.DoDataBind();
        }

        private void DoDataBind()
        {
            GridView1.DataSource = lstGroups;
            GridView1.Columns[6].Visible = true;
            GridView1.DataBind();
            GridView1.Columns[6].Visible = false;
        }

        protected void GridView1_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            DoDataBind();
        }

        protected void GridView1_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int groupID = int.Parse(GridView1.Rows[e.RowIndex].Cells[6].Text);
            if (groupID > 0)
            {
                string oldGroup = "";
                Group updatedGroup = null;
                foreach (Group g in lstGroups)
                {
                    if (g.Name == GridView1.Rows[e.RowIndex].Cells[2].Text && g.ID != groupID)
                    {
                        e.Cancel = true;
                        return;
                    }
                    if (g.ID == groupID)
                        updatedGroup = g;
                }
                if (updatedGroup != null)
                {
                    oldGroup = updatedGroup.Name;
                    updatedGroup.Name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].FindControl("NameTextBox")).Text;
                    updatedGroup.LastUpdatedBy = Utility.GetUserFullName();
                    updatedGroup.LastUpdatedDate = DateTime.UtcNow;
                    updatedGroup.PersonID = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;
                    TasksServiceClient tasksClient = new TasksServiceClient();
                    try
                    {
                        tasksClient.UpdateGroup(updatedGroup);
                        GridView1.EditIndex = -1;
                    }
                    catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
                    {
                        updatedGroup.Name = oldGroup;
                        if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                        {
                            Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                        }
                        else
                            Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "GRP_SAVE_UNKWNERR"), "Error", true);
                    }
                    catch
                    {
                        updatedGroup.Name = oldGroup;
                        Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "GRP_SAVE_UNKWNERR"), "Error", true);
                    }
                    ViewState["Groups"] = lstGroups;
                    tasksClient.Close();
                }
            }
            DoDataBind();
        }

        protected void GridView1_OnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            DoDataBind();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int groupID = int.Parse(GridView1.Rows[e.RowIndex].Cells[6].Text);
            if (groupID > 0)
            {
                Group updatedGroup = null;
                foreach (Group c in lstGroups)
                {
                    if (c.ID == groupID)
                    {
                        updatedGroup = c;
                        break;
                    }
                }
                if (updatedGroup != null)
                {
                    TasksServiceClient tasksClient = new TasksServiceClient();
                    updatedGroup.LastUpdatedBy = Utility.GetUserFullName();
                    updatedGroup.PersonID = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;
                    try
                    {
                        tasksClient.DeleteGroup(updatedGroup);
                        lstGroups.Remove(updatedGroup);
                        ViewState["Groups"] = lstGroups;
                    }
                    catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
                    {
                        if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                        {
                            Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                        }
                        else
                            Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "GRP_SAVE_UNKWNERR"), "Error", true);
                    }
                    catch
                    {
                        Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "GRP_SAVE_UNKWNERR"), "Error", true);
                    }
                    tasksClient.Close();
                }
            }
            DoDataBind();
        }

        protected void btnNewGroup_Click(object sender, EventArgs e)
        {

            foreach (Group c in lstGroups)
            {
                if (c.Name == txtNewGroup.Text)
                {
                    Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "GRP_EXISTS"), "Error", true);
                    return;
                }
            }
            Group newGroup = new Group();
            newGroup.Name = txtNewGroup.Text;
            newGroup.LastUpdatedBy = Utility.GetUserFullName();
            newGroup.LastUpdatedDate = DateTime.UtcNow;
            newGroup.TaskCount = 0;
            newGroup.Active = true;
            newGroup.PersonID = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;
            TasksServiceClient tasksClient = new TasksServiceClient();
            try
            {
                int iGroupID = tasksClient.AddGroup(newGroup);
                newGroup.ID = iGroupID;
                lstGroups.Add(newGroup);
                ViewState["Groups"] = lstGroups;
                txtNewGroup.Text = "";
            }
            catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
            {
                if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                {
                    Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                }
                else
                    Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "GRP_SAVE_UNKWNERR"), "Error", true);
            }
            catch
            {
                Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "GRP_SAVE_UNKWNERR"), "Error", true);
            }
            tasksClient.Close();
            DoDataBind();
        }
    }

    class GroupComparer : IComparer<Group>
    {
        SortDirection sortDir = SortDirection.Ascending;
        string sortExpr = "";
        public GroupComparer(SortDirection sortDirection, string sortExpression)
        {
            sortDir = sortDirection;
            sortExpr = sortExpression;
        }

        public int Compare(Group x, Group y)
        {
            switch (sortExpr)
            {
                case "Name":
                    if (sortDir == SortDirection.Ascending)
                        return StringComparer.CurrentCultureIgnoreCase.Compare(x.Name, y.Name);
                    else
                        return StringComparer.CurrentCultureIgnoreCase.Compare(y.Name, x.Name);
                case "LastUpdatedDate":
                    if (sortDir == SortDirection.Ascending)
                        return DateTime.Compare(x.LastUpdatedDate, y.LastUpdatedDate);
                    else
                        return DateTime.Compare(y.LastUpdatedDate, x.LastUpdatedDate);
                case "TaskCount":
                    if (sortDir == SortDirection.Ascending)
                        if (x.TaskCount > y.TaskCount)
                            return 1;
                        else if (x.TaskCount < y.TaskCount)
                            return -1;
                        else
                            return 0;
                    else
                        if (y.TaskCount > x.TaskCount)
                            return 1;
                        else if (y.TaskCount < x.TaskCount)
                            return -1;
                        else
                            return 0;
            }
            return 0;
        }

    }
}
